<template>
  <div class="defect-analysis" v-loading="loading">
    <!-- 缺陷帕累托图 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>缺陷帕累托分析</span>
            <el-tooltip content="帕累托图展示各类缺陷的数量及累计百分比，帮助识别关键缺陷类型" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </div>
          <div class="chart-container" ref="paretoChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- TOP缺陷趋势分析 -->
    <el-row :gutter="20" class="chart-row" v-if="topDefects && topDefects.length > 0">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>TOP缺陷月度趋势</span>
            <el-tooltip content="展示主要缺陷类型的月度发生趋势" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </div>
          <div class="defect-trends">
            <el-row :gutter="20">
              <el-col :xs="24" :sm="24" :md="8" v-for="(defect, index) in topDefects.slice(0, 3)" :key="defect.id">
                <div class="mini-chart-wrapper">
                  <div class="mini-chart-title">{{ defect.defectName }} ({{ defect.count }}次)</div>
                  <div class="mini-chart-container" :ref="`miniChart${index}`"></div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: "DefectAnalysis",
  props: {
    queryParams: {
      type: Object,
      required: true
    },
    chartData: {
      type: Object,
      required: true
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      paretoChart: null,
      miniCharts: []
    }
  },
  computed: {
    topDefects() {
      return this.chartData.topDefects || [];
    }
  },
  watch: {
    'chartData': {
      handler() {
        this.$nextTick(() => {
          this.initCharts();
        });
      },
      deep: true
    },
    'loading': {
      handler(newVal) {
        if (!newVal) {
          this.$nextTick(() => {
            this.initCharts();
          });
        }
      }
    },
    'topDefects': {
      handler() {
        this.$nextTick(() => {
          this.initMiniCharts();
        });
      },
      deep: true
    }
  },
  mounted() {
    this.initCharts();
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts);
    this.disposeCharts();
  },
  methods: {
    initCharts() {
      this.initParetoChart();
      this.initMiniCharts();
    },
    
    resizeCharts() {
      this.paretoChart?.resize();
      this.miniCharts.forEach(chart => {
        chart?.resize();
      });
    },
    
    disposeCharts() {
      this.paretoChart?.dispose();
      this.miniCharts.forEach(chart => {
        chart?.dispose();
      });
      this.miniCharts = [];
    },
    
    initParetoChart() {
      if (!this.$refs.paretoChart) return;
      
      if (this.paretoChart) {
        this.paretoChart.dispose();
      }
      
      this.paretoChart = echarts.init(this.$refs.paretoChart);
      
      const paretoData = this.chartData.paretoData || [];
      if (paretoData.length === 0) return;
      
      // 将数据按缺陷数量从大到小排序
      const sortedData = [...paretoData].sort((a, b) => b.count - a.count);
      
      const xData = sortedData.map(item => item.defectName);
      const countData = sortedData.map(item => item.count);
      const percentData = sortedData.map(item => item.cumulativePercentage);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            const count = params[0].value;
            const percent = params[1].value;
            return `${params[0].name}<br/>
                   数量: ${count}<br/>
                   累计占比: ${percent}%`;
          }
        },
        grid: {
          left: '3%',
          right: '5%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xData,
          axisLabel: {
            rotate: xData.length > 5 ? 45 : 0,
            interval: 0,
            fontSize: xData.length > 10 ? 10 : 12
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '缺陷数量',
            position: 'left'
          },
          {
            type: 'value',
            name: '累计百分比',
            position: 'right',
            min: 0,
            max: 100,
            axisLabel: {
              formatter: '{value}%'
            }
          }
        ],
        series: [
          {
            name: '缺陷数量',
            type: 'bar',
            data: countData,
            barWidth: '40%',
            itemStyle: {
              color: '#5470c6'
            }
          },
          {
            name: '累计百分比',
            type: 'line',
            yAxisIndex: 1,
            data: percentData,
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#ee6666'
            },
            lineStyle: {
              width: 2
            }
          }
        ]
      };
      
      this.paretoChart.setOption(option);
    },
    
    initMiniCharts() {
      // 清除之前的迷你图表
      this.miniCharts.forEach(chart => {
        chart?.dispose();
      });
      this.miniCharts = [];
      
      // 为TOP缺陷创建迷你趋势图
      this.topDefects.slice(0, 3).forEach((defect, index) => {
        this.$nextTick(() => {
          const chartRef = this.$refs[`miniChart${index}`];
          if (!chartRef || !chartRef[0]) return;
          
          const miniChart = echarts.init(chartRef[0]);
          
          const trendData = defect.trendData || [];
          const xData = trendData.map(item => item.month);
          const yData = trendData.map(item => item.count);
          
          const option = {
            tooltip: {
              trigger: 'axis',
              formatter: '{b}: {c}次'
            },
            grid: {
              top: 10,
              right: 10,
              bottom: 10,
              left: 10,
              containLabel: false
            },
            xAxis: {
              type: 'category',
              show: false,
              data: xData
            },
            yAxis: {
              type: 'value',
              show: false
            },
            series: [
              {
                data: yData,
                type: 'line',
                symbol: 'circle',
                symbolSize: 4,
                lineStyle: {
                  width: 2,
                  color: this.getTrendColor(yData)
                },
                areaStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: this.getTrendColor(yData, 0.3) },
                    { offset: 1, color: this.getTrendColor(yData, 0.1) }
                  ])
                }
              }
            ]
          };
          
          miniChart.setOption(option);
          this.miniCharts.push(miniChart);
        });
      });
    },
    
    // 根据严重程度生成对应的Tag类型
    getSeverityTag(level) {
      if (!level) return '';
      switch (parseInt(level)) {
        case 1: return 'success';  // 轻微
        case 2: return 'warning';  // 一般
        case 3: return 'danger';   // 严重
        case 4: return '';         // 致命，使用默认颜色（深红色）
        default: return 'info';
      }
    },
    
    // 生成模拟趋势数据（在实际应用中应从后端获取）
    generateMockTrendData(points, currentValue) {
      const data = [];
      const min = Math.max(1, currentValue - 5);
      const max = currentValue + 5;
      
      for (let i = 0; i < points - 1; i++) {
        data.push(Math.floor(Math.random() * (max - min + 1) + min));
      }
      
      // 最后一个点使用当前值
      data.push(currentValue);
      
      return data;
    },
    
    // 获取趋势颜色
    getTrendColor(data, alpha = 1) {
      const len = data.length;
      if (len < 2) return `rgba(24, 144, 255, ${alpha})`;
      
      const firstVal = data[0];
      const lastVal = data[len - 1];
      
      if (lastVal > firstVal) {
        // 上升趋势，使用红色
        return `rgba(245, 108, 108, ${alpha})`;
      } else if (lastVal < firstVal) {
        // 下降趋势，使用绿色
        return `rgba(103, 194, 58, ${alpha})`;
      } else {
        // 持平，使用蓝色
        return `rgba(24, 144, 255, ${alpha})`;
      }
    }
  }
}
</script>

<style scoped>
.defect-analysis {
  padding: 10px 0;
}
.chart-row {
  margin-bottom: 20px;
}
.chart-card {
  height: 100%;
}
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.chart-container {
  height: 300px;
  width: 100%;
}
.defect-trends {
  padding: 10px;
}
.mini-chart-wrapper {
  text-align: center;
  border: 1px solid #e6ebf5;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
  background: #fafafa;
}
.mini-chart-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 10px;
}
.mini-chart-container {
  height: 120px;
  width: 100%;
}
</style> 